package com.joymart.compute.service;

import com.joymart.common.model.Range;
import com.joymart.common.system.IdGenerator;
import com.joymart.common.utils.DatetimeUtils;
import com.joymart.compute.model.SalesPv;
import com.joymart.compute.repository.SalesPvRepository;
import com.joymart.order.model.Order;
import com.joymart.user.model.BusinessRole;
import com.joymart.user.model.CachedUser;
import com.joymart.user.service.UserCacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jdbc.core.JdbcAggregateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Optional;


@Service
public class SalesPvService {

    @Autowired
    private UserCacheManager userCacheManager;

    @Autowired
    private SalesPvRepository salesPvRepository;

    @Autowired
    private JdbcAggregateTemplate jdbcAggregateTemplate;

    @Autowired
    private IdGenerator idGenerator;

    @Transactional
    public void computeSalesPv(Order order) {
        SalesPv salesPv = new SalesPv();
        salesPv.setId(idGenerator.next());
        salesPv.setOrderId(order.getId());
        salesPv.setAmount(order.getTotalPv());
        salesPv.setContributorId(order.getBuyerId());
        salesPv.setOwnerId(order.getFirstSellerId());
        salesPv.setCreatedAt(DatetimeUtils.now());
        jdbcAggregateTemplate.insert(salesPv);
    }


    public BigDecimal getSalesPv(String ownerId, Range range) {
       if(userCacheManager.get(ownerId).getHighestRole().compareTo(BusinessRole.AU_CSR)<=0){
           return BigDecimal.ZERO; //店铺以下，不可能产生PV
       }
       return Optional.ofNullable( salesPvRepository.sumSalesPv(ownerId, range.getStart(), range.getEnd()))
               .orElse(BigDecimal.ZERO);
    }

}
